package com.yuntoyun.codeavatar.app.fwcore.plug.share.wechat;

import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;

import com.tencent.mm.opensdk.modelmsg.GetMessageFromWX;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXAppExtendObject;
import com.tencent.mm.opensdk.modelmsg.WXEmojiObject;
import com.tencent.mm.opensdk.modelmsg.WXFileObject;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMusicObject;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.modelmsg.WXVideoObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yuntoyun.fwcore.config.FwAppConfig;
import com.yuntoyun.fwcore.util.FwLogUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;

public class PlugWxShare {

    private final String tag = "WxShare";
    private final int TIMELINE_SUPPORTED_VERSION = 0x21020001;
    private final int THUMB_SIZE = 150;
    private Activity activity;

    // IWXAPI 是第三方app和微信通信的openapi接口
    private IWXAPI api;
    //
    private String targetOpenId;

    public PlugWxShare(Activity activity) {
        this.activity = activity;
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(activity, FwAppConfig.WECHAT_APPID, false);
        registerApp();
    }

    private void registerApp() {
        // 将该app注册到微信
        api.registerApp(FwAppConfig.WECHAT_APPID);
    }

    public void unregisterApp() {
        api.unregisterApp();
    }

    public void setOpenId(String targetOpenId) {
        this.targetOpenId = targetOpenId;
    }

    public boolean launchWechat() {
        return api.openWXApp();
    }

    public boolean isSupportedFriends() {
        int wxSdkVersion = api.getWXAppSupportAPI();
        return (wxSdkVersion >= TIMELINE_SUPPORTED_VERSION);
    }

    /////////
    ///分享信息
    /////////

    public void sendText(String text, WxSceneType sceneType) {
        // 初始化一个WXTextObject对象
        WXTextObject textObj = new WXTextObject();
        textObj.text = text;

        // 用WXTextObject对象初始化一个WXMediaMessage对象
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = textObj;
        // 发送文本类型的消息时，title字段不起作用
        // msg.title = "Will be ignored";
        msg.description = text;

        // 构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("text"); // transaction字段用于唯一标识一个请求
        req.message = msg;
        switch (sceneType) {
            case TimeLine:
                req.scene = SendMessageToWX.Req.WXSceneTimeline;
                break;
            case Session:
                req.scene = SendMessageToWX.Req.WXSceneSession;
                break;
            case Favorite:
                req.scene = SendMessageToWX.Req.WXSceneFavorite;
                break;
        }
        req.openId = this.targetOpenId;
        // 调用api接口发送数据到微信
        api.sendReq(req);
    }

    public void sendImage(Resources res, int resImgId, WxSceneType sceneType) {
        Bitmap bmp = BitmapFactory.decodeResource(res, resImgId);
        sendImage(bmp, sceneType);
    }

    public void sendImage(Bitmap bmp, WxSceneType sceneType) {
        WXImageObject imgObj = new WXImageObject(bmp);

        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;

        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
        bmp.recycle();
        msg.thumbData = Util.bmpToByteArray(thumbBmp, true);  // 设置缩略图

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("img");
        req.message = msg;
        switch (sceneType) {
            case TimeLine:
                req.scene = SendMessageToWX.Req.WXSceneTimeline;
                break;
            case Session:
                req.scene = SendMessageToWX.Req.WXSceneSession;
                break;
            case Favorite:
                req.scene = SendMessageToWX.Req.WXSceneFavorite;
                break;
        }
        req.openId = this.targetOpenId;
        api.sendReq(req);
    }

    public void sendImage(File imageFile, WxSceneType sceneType) {

        if (null == imageFile)
            return;

        if (!imageFile.exists())
            return;

        WXImageObject imgObj = new WXImageObject();
        imgObj.setImagePath(imageFile.getAbsolutePath());

        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;

        Bitmap bmp = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
        bmp.recycle();
        msg.thumbData = Util.bmpToByteArray(thumbBmp, true);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("img");
        req.message = msg;
        switch (sceneType) {
            case TimeLine:
                req.scene = SendMessageToWX.Req.WXSceneTimeline;
                break;
            case Session:
                req.scene = SendMessageToWX.Req.WXSceneSession;
                break;
            case Favorite:
                req.scene = SendMessageToWX.Req.WXSceneFavorite;
                break;
        }
        req.openId = this.targetOpenId;
        api.sendReq(req);
    }

    public void sendImage(String imageUrl, WxSceneType sceneType) {
        try {

            Bitmap bmp = BitmapFactory.decodeStream(new URL(imageUrl).openStream());

            WXImageObject imgObj = new WXImageObject();
            imgObj.imageData = Util.bmpToByteArray(bmp, true);

            WXMediaMessage msg = new WXMediaMessage();
            msg.mediaObject = imgObj;

            Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
            bmp.recycle();
            msg.thumbData = Util.bmpToByteArray(thumbBmp, true);

            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = buildTransaction("img");
            req.message = msg;
            switch (sceneType) {
                case TimeLine:
                    req.scene = SendMessageToWX.Req.WXSceneTimeline;
                    break;
                case Session:
                    req.scene = SendMessageToWX.Req.WXSceneSession;
                    break;
                case Favorite:
                    req.scene = SendMessageToWX.Req.WXSceneFavorite;
                    break;
            }
            req.openId = this.targetOpenId;
            api.sendReq(req);
        } catch (IOException e) {
            FwLogUtil.error(tag, e);
        } catch (Exception e) {
            FwLogUtil.error(tag, e);
        }
    }

    public void sendAudio(String audioUrl, boolean isLowBandUrl, String title, String
            description, Resources res, int resImgId, WxSceneType sceneType) {
        Bitmap thumb = BitmapFactory.decodeResource(res, resImgId);
        sendAudio(audioUrl, isLowBandUrl, title, description, thumb, sceneType);
    }

    public void sendAudio(String audioUrl, boolean isLowBandUrl, String title, String
            description, Bitmap thumb, WxSceneType sceneType) {
        WXMusicObject music = new WXMusicObject();

        //是否为低带宽
        if (isLowBandUrl) {
            music.musicLowBandUrl = audioUrl;
        } else {
            music.musicUrl = audioUrl;
        }

        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = music;
        if (!TextUtils.isEmpty(title))
            msg.title = title;
        if (!TextUtils.isEmpty(description))
            msg.description = description;
        if (null != thumb)
            msg.thumbData = Util.bmpToByteArray(thumb, true);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("music");
        req.message = msg;
        switch (sceneType) {
            case TimeLine:
                req.scene = SendMessageToWX.Req.WXSceneTimeline;
                break;
            case Session:
                req.scene = SendMessageToWX.Req.WXSceneSession;
                break;
            case Favorite:
                req.scene = SendMessageToWX.Req.WXSceneFavorite;
                break;
        }
        req.openId = this.targetOpenId;
        api.sendReq(req);
    }

    public void sendVideo(String videoUrl, boolean isLowBandUrl, String title, String
            description, Bitmap thumb, WxSceneType sceneType) {
        WXVideoObject audio = new WXVideoObject();

        //是否为低带宽
        if (isLowBandUrl) {
            audio.videoLowBandUrl = videoUrl;
        } else {
            audio.videoUrl = videoUrl;
        }

        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = audio;
        if (!TextUtils.isEmpty(title))
            msg.title = title;
        if (!TextUtils.isEmpty(description))
            msg.description = description;
        if (null != thumb)
            msg.thumbData = Util.bmpToByteArray(thumb, true);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("video");
        req.message = msg;
        switch (sceneType) {
            case TimeLine:
                req.scene = SendMessageToWX.Req.WXSceneTimeline;
                break;
            case Session:
                req.scene = SendMessageToWX.Req.WXSceneSession;
                break;
            case Favorite:
                req.scene = SendMessageToWX.Req.WXSceneFavorite;
                break;
        }
        req.openId = this.targetOpenId;
        api.sendReq(req);
    }

    public void sendWebpage(String webUrl, String title, String description, Bitmap thumb, Bitmap.CompressFormat format,
                            WxSceneType sceneType) {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = webUrl;

        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = webpage;
        if (!TextUtils.isEmpty(title))
            msg.title = title;
        if (!TextUtils.isEmpty(description))
            msg.description = description;
        if (null != thumb) {
            Bitmap thumbBmp = Bitmap.createScaledBitmap(thumb, THUMB_SIZE, THUMB_SIZE, true);
            thumb.recycle();
            msg.thumbData = Util.bmpToByteArray(thumbBmp, format, true);
        }

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        switch (sceneType) {
            case TimeLine:
                req.scene = SendMessageToWX.Req.WXSceneTimeline;
                break;
            case Session:
                req.scene = SendMessageToWX.Req.WXSceneSession;
                break;
            case Favorite:
                req.scene = SendMessageToWX.Req.WXSceneFavorite;
                break;
        }
        req.openId = this.targetOpenId;
        api.sendReq(req);
    }

    public void sendApp(String fileInfo, String title, String description, WxSceneType sceneType) {
        final WXAppExtendObject appdata = new WXAppExtendObject();
        appdata.extInfo = fileInfo;

        final WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = appdata;
        if (!TextUtils.isEmpty(title))
            msg.title = title;
        if (!TextUtils.isEmpty(description))
            msg.description = description;

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("appdata");
        req.message = msg;
        switch (sceneType) {
            case TimeLine:
                req.scene = SendMessageToWX.Req.WXSceneTimeline;
                break;
            case Session:
                req.scene = SendMessageToWX.Req.WXSceneSession;
                break;
            case Favorite:
                req.scene = SendMessageToWX.Req.WXSceneFavorite;
                break;
        }
        req.openId = this.targetOpenId;
        api.sendReq(req);
    }

    public void sendApp(File imageFile, String fileInfo, String title, String description,
                        WxSceneType sceneType) {
        if (null == imageFile)
            return;

        if (!imageFile.exists())
            return;

        final WXAppExtendObject appdata = new WXAppExtendObject();
        appdata.fileData = Util.readFromFile(imageFile.getAbsolutePath(), 0, -1);
        appdata.extInfo = fileInfo;

        final WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = appdata;
        if (!TextUtils.isEmpty(title))
            msg.title = title;
        if (!TextUtils.isEmpty(description))
            msg.description = description;
        msg.setThumbImage(Util.extractThumbNail(imageFile.getAbsolutePath(), THUMB_SIZE,
                THUMB_SIZE, true));

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("appdata");
        req.message = msg;
        switch (sceneType) {
            case TimeLine:
                req.scene = SendMessageToWX.Req.WXSceneTimeline;
                break;
            case Session:
                req.scene = SendMessageToWX.Req.WXSceneSession;
                break;
            case Favorite:
                req.scene = SendMessageToWX.Req.WXSceneFavorite;
                break;
        }
        req.openId = this.targetOpenId;
        api.sendReq(req);
    }

    public void sendEmoji(File gifFile, File thumbFile, boolean isByte, String title, String
            description, WxSceneType sceneType) {
        if (null == gifFile || null == thumbFile)
            return;

        if (!(gifFile.exists() && thumbFile.exists()))
            return;

        WXEmojiObject emoji = new WXEmojiObject();
        if (isByte) {
            emoji.emojiData = Util.readFromFile(gifFile.getAbsolutePath(), 0, (int) gifFile
                    .length());
        } else {
            emoji.emojiPath = gifFile.getAbsolutePath();
        }

        final WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = emoji;
        if (!TextUtils.isEmpty(title))
            msg.title = title;
        if (!TextUtils.isEmpty(description))
            msg.description = description;
        msg.thumbData = Util.readFromFile(thumbFile.getAbsolutePath(), 0, (int) thumbFile.length());

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("emoji");
        req.message = msg;
        switch (sceneType) {
            case TimeLine:
                req.scene = SendMessageToWX.Req.WXSceneTimeline;
                break;
            case Session:
                req.scene = SendMessageToWX.Req.WXSceneSession;
                break;
            case Favorite:
                req.scene = SendMessageToWX.Req.WXSceneFavorite;
                break;
        }
        req.openId = this.targetOpenId;
        api.sendReq(req);
    }

    public void sendFile(String imgPath, WxSceneType sceneType) {

        File file = new File(imgPath);
        if (!file.exists()) {
            return;
        }

        WXFileObject fileObject = new WXFileObject();
        fileObject.setFilePath(imgPath);

        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = fileObject;

        Bitmap bmp = BitmapFactory.decodeFile(imgPath);
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
        bmp.recycle();
        msg.thumbData = Util.bmpToByteArray(thumbBmp, true); // 设置缩略图

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("file");
        req.message = msg;
        switch (sceneType) {
            case TimeLine:
                req.scene = SendMessageToWX.Req.WXSceneTimeline;
                break;
            case Session:
                req.scene = SendMessageToWX.Req.WXSceneSession;
                break;
            case Favorite:
                req.scene = SendMessageToWX.Req.WXSceneFavorite;
                break;
        }
        req.openId = this.targetOpenId;
        api.sendReq(req);
    }

    public void sendFile(Resources res, int resImgId, WxSceneType sceneType) {
        Bitmap bmp = BitmapFactory.decodeResource(res, resImgId);
        byte[] dataBuf = null;
        try {
            final ByteArrayOutputStream os = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.JPEG, 85, os);
            dataBuf = os.toByteArray();
            os.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        WXFileObject fileObject = new WXFileObject(dataBuf);

        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = fileObject;

        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
        bmp.recycle();
        msg.thumbData = Util.bmpToByteArray(thumbBmp, true); // 设置缩略图

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("file");
        req.message = msg;
        switch (sceneType) {
            case TimeLine:
                req.scene = SendMessageToWX.Req.WXSceneTimeline;
                break;
            case Session:
                req.scene = SendMessageToWX.Req.WXSceneSession;
                break;
            case Favorite:
                req.scene = SendMessageToWX.Req.WXSceneFavorite;
                break;
        }
        req.openId = this.targetOpenId;
        api.sendReq(req);
    }

    public void respText(String text) {
        // 初始化一个WXTextObject对象
        WXTextObject textObj = new WXTextObject();
        textObj.text = text;

        // 用WXTextObject对象初始化一个WXMediaMessage对象
        WXMediaMessage msg = new WXMediaMessage(textObj);
        msg.description = text;

        // 构造一个Resp
        GetMessageFromWX.Resp resp = new GetMessageFromWX.Resp();
        // 将req的transaction设置到resp对象中，其中bundle为微信传递过来的intent所带的内容，通过getExtras方法获取
        resp.transaction = getTransaction();
        resp.message = msg;

        // 调用api接口响应数据到微信
        api.sendResp(resp);
    }

    public void respImage(Resources res, int resImgId) {
        // respond with image message
        Bitmap bmp = BitmapFactory.decodeResource(res, resImgId);
        WXImageObject imgObj = new WXImageObject(bmp);

        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;

        // 设置消息的缩略图
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
        bmp.recycle();
        msg.thumbData = Util.bmpToByteArray(thumbBmp, true);

        GetMessageFromWX.Resp resp = new GetMessageFromWX.Resp();
        resp.transaction = getTransaction();
        resp.message = msg;

        api.sendResp(resp);
    }

    public void getAccessToken(String scope) {

        if (TextUtils.isEmpty(scope)) {
            scope = "snsapi_userinfo";
        }

        // send oauth request
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = scope;
        req.state = "none";
        req.openId = this.targetOpenId;
        api.sendReq(req);
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System
                .currentTimeMillis();
    }

    private String getTransaction() {
        final GetMessageFromWX.Req req = new GetMessageFromWX.Req(activity.getIntent().getExtras());
        return req.transaction;
    }

//    // 微信发送请求到第三方应用时，会回调到该方法
//    @Override
//    public void onReq(BaseReq baseReq) {
//        switch (baseReq.getType()) {
//            case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
//                //由响应方法处理
//                break;
//            case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
//                ShowMessageFromWX.Req showReq = (ShowMessageFromWX.Req) baseReq;
//                if (null != showReq) {
//                    WXMediaMessage wxMsg = showReq.message;
//                    WXAppExtendObject obj = (WXAppExtendObject) wxMsg.mediaObject;
//
//                    //以上两实例处理逻辑省略
//                }
//                break;
//            case ConstantsAPI.COMMAND_LAUNCH_BY_WX:
//                //由微信启动应用
//                break;
//            default:
//                break;
//        }
//    }
//
//    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
//    @Override
//    public void onResp(BaseResp baseResp) {
//
//        //resp.openId //获取openId
//
//        if (baseResp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {
//            String resultCode = ((SendAuth.Resp) baseResp).code;
//        }
//
//        switch (baseResp.errCode) {
//            case BaseResp.ErrCode.ERR_OK:
//                //发送成功
//                break;
//            case BaseResp.ErrCode.ERR_USER_CANCEL:
//                //发送取消
//                break;
//            case BaseResp.ErrCode.ERR_AUTH_DENIED:
//                //发送被拒绝
//                break;
//            default:
//                //发送返回
//                break;
//        }
//    }
}
